package com.api.shop.util.fileUpload;

import com.api.shop.exception.MyDataException;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @Auther: wyx
 * @Date: 2019-04-09 12:14
 * @Description: 图片上传工具类
 */
public class FileUtils {

    public static String upload(MultipartFile avatar){
        //1定义要上传文件 的存放路径
         String localPath = "/usr/local/photos";
        //String localPath = "E:/image";
        //2获得文件名字
        String fileName = avatar.getOriginalFilename();
        //2上传失败提示
        String newFileName = FileUtils.upload(avatar, localPath, fileName);
        if(newFileName != null){
            //上传成功
            return "http://yjjvip.cn:8080/pictures/" + newFileName;
        }else{
            throw new MyDataException("头像上传失败，请重试");
        }
    }

    /**
     *
     * @param avatar 文件
     * @param path   文件存放路径
     * @param fileName 原文件名
     * @return
     */
    private static String upload(MultipartFile avatar, String path, String fileName){

        String newFileName = FileNameUtils.getFileName(fileName);

        // 生成新的文件名
        String realPath = path + "/" + newFileName;

        File dest = new File(realPath);

        //判断文件父目录是否存在
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdir();
        }

        try {
            //保存文件
            avatar.transferTo(dest);
            return newFileName;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }

}
